package com.peng.leetcode.list;

/**
 * ReverseKGroup2
 * 25. K 个一组翻转链表
 * https://leetcode.cn/problems/reverse-nodes-in-k-group/
 *
 * @author: lupeng6
 * @create: 2023/2/14 12:21
 */
public class ReverseKGroup2 {

    public static void main(String[] args) {
        ListNode node = new ReverseKGroup2().reverseKGroup(BuildListNode.tailInsert(1, 2, 3, 4, 5), 2);
        System.out.println(node);
    }

    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if (head == null) {
            return null;
        }
        ListNode curr = head;
        for (int i = 0; i < k; i++) {
            if (curr == null) {
                return head;
            }
            curr = curr.next;
        }

        // reverse
        ListNode prev = null;
        ListNode tail = head;
        while (head != curr) {
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        tail.next = reverseKGroup(curr, k);
        return prev;
    }
}
